package com.woman.beautylive.presentation.ui.main.find.pengyouquan;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.google.gson.Gson;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.woman.beautylive.BeautyLiveApplication;
import com.woman.beautylive.domain.LocalDataManager;
import com.woman.beautylive.presentation.ui.main.find.paihangbangbean.AvatarBeans;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;




public class UploadImage {
	private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
	private ExecutorService executorService;
	private static UploadImage upload;

	private OnUploadlistener uploadListener;
	private static Context context;
	

	private UploadImage() {
		executorService = Executors.newFixedThreadPool(4);
	}

	/**
	 * 单例
	 * 
	 * @return
	 */
	public static synchronized UploadImage getInstance() {
		if (upload == null) {
			upload = new UploadImage();
		}

		return upload;
	}

	public void execute(final String url, final OnUploadlistener uploadListener) {
		executorService.execute(new Runnable() {

			@Override
			public void run() {

				Handler handler = new Handler(Looper.getMainLooper()) {
					@Override
					public void handleMessage(Message msg) {
						switch (msg.what) {
						case 0:
							String resultData = msg.getData().getString("result");
							System.out.println("初始数据"+resultData);
							// requestCode =
							// msg.getData().getInt("requestCode");
							uploadListener.OnSuccess(resultData);
							break;
						case 1:
							String errorInfo = "上传失败";
							System.out.println("失败了");
							uploadListener.OnError(errorInfo);
							break;
						default:
							break;
						}

					}
				};

				try {
					OkHttpClient client = new OkHttpClient();
					client.setConnectTimeout(10, TimeUnit.SECONDS);
					client.setReadTimeout(10, TimeUnit.SECONDS);
					client.setWriteTimeout(10, TimeUnit.SECONDS);

					File file = new File(url);

					// 创建请求BODY
					RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
							.addFormDataPart("token", LocalDataManager.getInstance().getLoginInfo().getToken())
							.addFormDataPart("file[]", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file)).build();

					//
					// fBuilder.addFormDataPart("uid", "33");
					// fBuilder.addFormDataPart("type", "avatar");
					// fBuilder.type(MEDIA_TYPE_PNG);

					//
					// fBuilder.addFormDataPart("iamge", file.getName(),
					// RequestBody.create(MEDIA_TYPE_PNG, file));

					// RequestBody requestBody=new
					// MultipartBuilder().type(MultipartBuilder.FORM).addPart("uid","33");

					// RequestBody requestBody = fBuilder.build();
//http://www.51mry.cn/OpenAPI/v1/pengyou/uploadPic
					String uploadUrl="http://www.51mry.cn/OpenAPI/v1/pengyou/uploadPic";
					Request request = new Request.Builder()
							.url(uploadUrl)
							.post(requestBody).build();

					Response response = client.newCall(request).execute();
					if (!response.isSuccessful()) {
						handler.sendEmptyMessage(1);
					} else {
						String result = response.body().string();
						System.out.println("上传结果："+result);
						// if(code==0)
//						 JSONObject jsonObject = new JSONObject(result);
//						 String resultData = jsonObject.getJSONObject("data")+"";

						Gson gson = new Gson();
						AvatarBeans avatarBeans = gson.fromJson(result, AvatarBeans.class);// 获取到网络端数据,多个参数
						if (avatarBeans.getCode() == 0) {
							Message msg = new Message();
							msg.what = 0;
							Bundle bundle = new Bundle();
							bundle.putString("result", avatarBeans.getData().get(0));//单张上传，所以取第一张
							msg.setData(bundle);
							handler.sendMessage(msg);
							// SPUtils.put(App.ctx,null, SPContants.AVATAR_ID,
							// avatarBeans.getData().getId());

//							String url = (String) SPUtils.get(context, null, SPContants.AVATAR_URL, "");
//							if (!url.equals("")) {
//								SPUtils.remove(context, null, SPContants.AVATAR_URL);
//							}
//							SPUtils.put(context, null, SPContants.AVATAR_URL, avatarBeans.getData().getApi_img_url());
						}

					}
				} catch (Exception e) {
					e.printStackTrace();

				}
			}

		});
	}

	public  static String compress(String srcPath) {


		int sizeKB=500;  // 最大 600kB
		float hh =  720;
		float ww = 480;
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, opts);
		opts.inJustDecodeBounds = false;
		int w = opts.outWidth;
		int h = opts.outHeight;
		int size = 0;
		if (w <= ww && h <= hh) {
			size = 1;
		} else {
			double scale = w >= h ? w / ww : h / hh;
			double log = Math.log(scale) / Math.log(2);
			double logCeil = Math.ceil(log);
			size = 2;
		}
		opts.inSampleSize = size;
		bitmap = BitmapFactory.decodeFile(srcPath, opts);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int quality = 100;
		bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
		System.out.println(baos.toByteArray().length);
		while (baos.toByteArray().length > sizeKB * 1024) {
			baos.reset();
			quality -= 20;
			bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

			System.out.println(baos.toByteArray().length);
		}
		try {
			File file=new File(BeautyLiveApplication.getContextInstance().getCacheDir(),System.currentTimeMillis()+".jpg") ;
			baos.writeTo(new FileOutputStream( file ));
			return file.getCanonicalPath();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				baos.flush();
				baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 读取照片exif信息中的旋转角度
	 *
	 * @param path 照片路径
	 * @return角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 
	 * @author winter 要实现的接口
	 */

	public interface OnUploadlistener {

		public void OnSuccess(String resultData);

		public void OnError(String resultData);

	}

}
